﻿//-----------------------------------------------------------------------
// <Copyright>
// * Copyright (C) 2022 RuYiAdmin All Rights Reserved
// </Copyright>
//-----------------------------------------------------------------------

using Nest;
using RuYiAdmin.Net.Entity.CoreEnum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.Entity.CoreEntity
{
    /// <summary>
    /// SearchRequest查询条件
    /// </summary>
    public class SearchRequestCondition
    {
        /// <summary>
        /// 起始页
        /// </summary>
        public int PageIndex { get; set; }

        /// <summary>
        /// 分页数量
        /// </summary>
        public int PageSize { get; set; }

        /// <summary>
        /// 排序字段
        /// </summary>
        public String Sort { get; set; }

        /// <summary>
        /// 搜索条件
        /// </summary>
        public List<SearchItem> SearchItems { get; set; }

        /// <summary>
        /// 无参构造函数
        /// </summary>
        public SearchRequestCondition()
        {

        }

        /// <summary>
        /// 有参构造函数
        /// </summary>
        /// <param name="pageIndex">起始页</param>
        /// <param name="pageSize">分页数量</param>
        /// <param name="sort">排序字段</param>
        /// <param name="searchItems">搜索条件</param>
        public SearchRequestCondition(int pageIndex, int pageSize, String sort, List<SearchItem> searchItems)
        {
            PageIndex = pageIndex;
            PageSize = pageSize;
            Sort = sort;
            SearchItems = searchItems;
        }

        /// <summary>
        /// 转化为SearchRequest
        /// </summary>
        /// <returns></returns>
        public SearchRequest ConvertToSearchRequest()
        {
            var searchRequest = new SearchRequest()
            {
                From = this.PageIndex,
                Size = this.PageSize
            };

            BoolQuery bq = new BoolQuery();
            List<QueryContainer> list = new List<QueryContainer>();

            foreach (var item in SearchItems)
            {
                if (item.SearchType == SearchType.TermQuery)
                {
                    list.Add(new TermQuery()
                    {
                        Field = item.Field,
                        Value = item.Value
                    });
                }
                else if (item.SearchType == SearchType.MatchQuery)
                {
                    list.Add(new MatchQuery()
                    {
                        Field = item.Field,
                        Query = item.Value.ToString()
                    });
                }
            }

            bq.Must = list.ToArray();
            searchRequest.Query = bq;

            return searchRequest;
        }
    }
}
